package com.rul.mars.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.rul.mars.common.api.CommonResult;
import com.rul.mars.common.constant.DeleteStatusConstant;
import com.rul.mars.common.constant.OrderStatusConstant;
import com.rul.mars.common.constant.OrderTypeConstant;
import com.rul.mars.common.constant.PickupTypeConstant;
import com.rul.mars.common.exception.Asserts;
import com.rul.mars.common.service.RedisService;
import com.rul.mars.mbg.dao.OrderDao;
import com.rul.mars.mbg.domain.*;
import com.rul.mars.mbg.mapper.OrderMapper;
import com.rul.mars.mbg.mapper.ProductMapper;
import com.rul.mars.mbg.model.*;
import com.rul.mars.order.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 订单服务实现
 *
 * @author RuL
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Value("${order.timeout}")
    private Long ORDER_TIMEOUT;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OrderDao orderDao;

    @Autowired
    private UserService userService;
    @Autowired
    private UserAddressService userAddressService;
    @Autowired
    private ShopService shopService;
    @Autowired
    private LeaseService leaseService;
    @Autowired
    private ProductService productService;

    @Autowired
    private StockService stockService;
    @Autowired
    private RedisService redisService;

    @Value("${redis.key.orderId}")
    private String REDIS_KEY_ORDER_ID;
    @Value("${redis.database}")
    private String REDIS_DATABASE;

    /**
     * 根据订单id查询订单详情
     *
     * @param id 订单ID
     * @return 订单详情
     */
    @Override
    public OrderDetail detail(Long id) {
        Order order = orderMapper.selectByPrimaryKey(id);
        return BeanUtil.copyProperties(order, OrderDetail.class);
    }

    /**
     * 根据订单ID取消订单
     *
     * @param id 订单ID
     * @return 订单取消结果
     */
    @Override
    @Transactional
    public boolean cancelOrder(Long id) {
        //查询订单信息
        Order order = orderMapper.selectByPrimaryKey(id);
        //订单状态设置为取消
        order.setOrderStatus(OrderStatusConstant.CANCELED);
        int rows = orderMapper.updateByPrimaryKeySelective(order);

        if (rows == 1) {
            stockService.unlockStock(order.getProductId(), order.getProductNumber());
            return true;
        }
        return false;
    }

    /**
     * 用户确认收货
     *
     * @param id 订单ID
     */
    @Override
    public void confirmReceive(Long id) {
        Order order = orderMapper.selectByPrimaryKey(id);
        //设置订单状态为已收货
        order.setOrderStatus(OrderStatusConstant.RECEIVED);
        orderMapper.updateByPrimaryKeySelective(order);

        //增加商品销量
        Product product = productMapper.selectByPrimaryKey(order.getProductId());
        product.setSaleNum(product.getSaleNum() + order.getProductNumber());
        productMapper.updateByPrimaryKeySelective(product);
    }

    /**
     * 用户删除订单
     *
     * @param id 订单ID
     * @return 操作结果
     */
    @Override
    public boolean deleteOrder(Long id) {
        Order order = orderMapper.selectByPrimaryKey(id);

        if (order.getOrderStatus() < OrderStatusConstant.RECEIVED) {
            Asserts.fail("不能删除未收货的订单");
        }
        //设置订单删除状态为已删除
        order.setDeleteStatus(DeleteStatusConstant.YES);
        int rows = orderMapper.updateByPrimaryKeySelective(order);
        //返回修改结果
        return rows == 1;
    }

    /**
     * 直接购买生成订单
     *
     * @param orderParam 生成订单相关参数
     * @return 生成的订单详情
     */
    @Override
    public OrderDetail generateOrder(OrderParam orderParam) {
        //用户信息
        User user = userService.currentUser();
        //商品信息
        Product product = productMapper.selectByPrimaryKey(orderParam.getProductId());
        Integer productNumber = orderParam.getProductNumber();
        if (product.getStock() < productNumber) {
            Asserts.fail("库存不足");
        } else {
            //锁定库存
            stockService.lockStock(product.getId(), productNumber);
        }

        //将OrderParam转化为Order
        Order order = BeanUtil.copyProperties(orderParam, Order.class);

        //售价
        BigDecimal sellPrice = product.getSellPrice();
        //订单总金额
        BigDecimal totalAmount = sellPrice.multiply(new BigDecimal(productNumber));
        if (orderParam.getOrderType().equals(OrderTypeConstant.OUTRIGHT_PURCHASE)
                && orderParam.getPickupType().equals(PickupTypeConstant.DELIVERY)) {
            //直接购买且取件方式为送货上门,订单总金额加上运费
            totalAmount = totalAmount.add(product.getFreightAmount());
            //设置订单运费
            order.setFreightAmount(product.getFreightAmount());
        }

        //收货地址信息
        ReceiveAddressDetail addressDetail = userAddressService.detail(orderParam.getReceiveAddressId());

        //设置订单总金额
        order.setTotalAmount(totalAmount);
        //设置单价
        order.setUnitPrice(sellPrice);

        //设置用户ID
        order.setUserId(user.getId());
        //订单状态为未支付
        order.setOrderStatus(OrderStatusConstant.NON_PAYMENT);
        //设置订单编号
        order.setOrderSn(generateOrderSn(order));
        //设置店铺ID
        order.setShopId(product.getShopId());

        //设置收货信息
        order.setReceiverName(addressDetail.getName());
        order.setReceiverPhone(addressDetail.getPhoneNumber());
        order.setReceiverProvince(addressDetail.getProvince());
        order.setReceiverCity(addressDetail.getCity());
        order.setReceiverRegion(addressDetail.getRegion());
        order.setReceiverDetailAddress(addressDetail.getDetailAddress());

        orderMapper.insertSelective(order);
        //订单信息转为订单详情信息
        return BeanUtil.copyProperties(order, OrderDetail.class);
    }

    /**
     * 商家发货
     *
     * @param param 发货参数
     * @return 发货结果
     */
    @Override
    public boolean delivery(DeliveryParam param) {
        Order order = orderMapper.selectByPrimaryKey(param.getId());
        //设置订单状态为已发货（待收货）
        order.setOrderStatus(OrderStatusConstant.NON_RECEIVED);
        //设置订单物流公司
        order.setDeliveryCompany(param.getDeliveryCompany());
        //设置订单物流编号
        order.setDeliverySn(param.getDeliverySn());

        int rows = orderMapper.updateByPrimaryKeySelective(order);
        return rows == 1;
    }

    /**
     * 按条件查询订单信息
     *
     * @param queryParam 查询条件
     * @param pageNum    页面号
     * @param pageSize   页面大小
     * @return 符合条件的结果
     */
    @Override
    public List<Order> listOrder(OrderQueryParam queryParam, Integer pageNum, Integer pageSize) {
        //设置分页信息
        PageHelper.startPage(pageNum, pageSize);
        //当前店铺信息
        Shop currentShop = shopService.current();
        //查询参数shopId设置为当前店铺信息
        queryParam.setShopId(currentShop.getId());
        //查询信息并返回
        return orderDao.getList(queryParam);
    }

    /**
     * 取消超时订单
     *
     * @return 取消数量
     */
    @Override
    public Integer cancelTimeOutOrder() {
        Timestamp lastCreateTime = new Timestamp(System.currentTimeMillis() - ORDER_TIMEOUT);
        OrderExample example = new OrderExample();
        example.createCriteria()
                .andCreateTimeLessThan(lastCreateTime)
                .andDeleteStatusEqualTo(DeleteStatusConstant.NO)
                .andOrderStatusEqualTo(OrderStatusConstant.NON_PAYMENT);

        //所有超时订单
        List<Order> timeoutOrder = orderMapper.selectByExample(example);
        for (Order order : timeoutOrder) {
            //订单状态设为已经取消
            order.setOrderStatus(OrderStatusConstant.CANCELED);
            //解锁库存
            stockService.unlockStock(order.getProductId(), order.getProductNumber());
            orderMapper.updateByPrimaryKey(order);
        }
        return null;
    }

    /**
     * 根据租赁单生成订单
     *
     * @param leaseId 租赁单ID
     * @return 生成的订单详情
     */
    @Override
    public OrderDetail generateOrder(Long leaseId) {
        LeaseDetail leaseDetail = leaseService.detail(leaseId);
        ProductDetail productDetail = productService.detail(leaseDetail.getProductId()).getData();
        Order order = BeanUtil.copyProperties(leaseDetail, Order.class);
        order.setId(null);
        //订单编号
        order.setOrderSn(leaseDetail.getLeaseSn());
        //订单状态
        order.setOrderType(OrderTypeConstant.RENTED_PURCHASE);
        //售价
        order.setUnitPrice(productDetail.getSellPrice());
        //设置订单完成时间
        order.setFinishedTime(new Timestamp(System.currentTimeMillis()));
        orderMapper.insertSelective(order);
        //返回订单详情
        return BeanUtil.copyProperties(order, OrderDetail.class);
    }

    /**
     * 生成18位订单编号:8位日期+2位订单类型+2位支付方式+6位以上自增id
     *
     * @param order 订单
     * @return 18位订单编号
     */
    private String generateOrderSn(Order order) {
        StringBuilder sb = new StringBuilder();
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String key = REDIS_DATABASE + REDIS_KEY_ORDER_ID + date;
        Long increment = redisService.incr(key, 1);
        sb.append(date);
        sb.append(String.format("%02d", order.getOrderType()));
        sb.append(String.format("%02d", order.getPayType()));
        String incrementStr = increment.toString();
        if (incrementStr.length() <= 6) {
            sb.append(String.format("%06d", increment));
        } else {
            sb.append(incrementStr);
        }
        return sb.toString();
    }


}
